/*
 * @Author: i@rysa.cn
 * @Date: 2022-05-14 17:02:20
 * @LastEditTime: 2022-07-26 09:43:56
 * @LastEditors: i@rysa.cn
 * @Description:
 * @FilePath: \go-utils\wechat\pay\h5.go
 */
package pay

import (
	"github.com/wechatpay-apiv3/wechatpay-go/core"
	"github.com/wechatpay-apiv3/wechatpay-go/services/payments"
	pay_h5 "github.com/wechatpay-apiv3/wechatpay-go/services/payments/h5"
)

type h5 struct {
	*PayConfig
}

func NewH5(cfg *PayConfig) *h5 {
	return &h5{cfg}
}

func (p *h5) PrepayOrder(prepay OrderRequest) (*pay_h5.PrepayResponse, *core.APIResult, error) {
	client, ctx, err := GetClient(p.PayConfig)
	if err != nil {
		return nil, nil, err
	}
	svc := pay_h5.H5ApiService{Client: client}
	resp, result, err := svc.Prepay(ctx, pay_h5.PrepayRequest{
		Appid:       core.String(p.Appid),
		Mchid:       core.String(p.MchId),
		Description: core.String(prepay.Description),
		OutTradeNo:  core.String(prepay.OutTradeNo),
		Attach:      core.String(prepay.Attach),
		NotifyUrl:   core.String(p.Notify),
		Amount: &pay_h5.Amount{
			Total: core.Int64(int64(prepay.Amount * 100)),
		},
		SceneInfo: &pay_h5.SceneInfo{
			PayerClientIp: core.String(prepay.ClientIp),
			H5Info: &pay_h5.H5Info{
				Type: core.String(prepay.H5Info),
			},
		},
	})
	return resp, result, err
}

func (p *h5) QueryOrderByTransactionId(transactionId string) (*payments.Transaction, *core.APIResult, error) {
	client, ctx, err := GetClient(p.PayConfig)
	if err != nil {
		return nil, nil, err
	}
	svc := pay_h5.H5ApiService{Client: client}
	return svc.QueryOrderById(ctx, pay_h5.QueryOrderByIdRequest{
		Mchid:         core.String(p.MchId),
		TransactionId: core.String(transactionId),
	})
}

func (p *h5) QueryOrderByOutTradeNo(outNo string) (*payments.Transaction, *core.APIResult, error) {
	client, ctx, err := GetClient(p.PayConfig)
	if err != nil {
		return nil, nil, err
	}
	svc := pay_h5.H5ApiService{Client: client}
	return svc.QueryOrderByOutTradeNo(ctx, pay_h5.QueryOrderByOutTradeNoRequest{
		Mchid:      core.String(p.MchId),
		OutTradeNo: core.String(outNo),
	})
}
